from pymongo import MongoClient,ASCENDING,DESCENDING
from bson.objectid import ObjectId


class LearnMongoDB(object):
    def __init__(self):
        self.client = MongoClient("mongodb://localhost:27017/")
        self.db = self.client.test

    def add_one(self):
        # 新增一个文档
        doc = {
            "name": "张三1",
            "age": 21
        }
        result = self.db.student.insert_one(doc)
        print(result)
        print(result.inserted_id)

    def add_many(self):
        # 新增多个文档
        doc1 = {
            "name": "张三2",
            "age": 21
        }
        doc2 = {
            "name": "张三3",
            "age": 21
        }
        doc_list = [doc1,doc2]
        result = self.db.student.insert_many(doc_list)
        print(result)
        print(result.inserted_ids)

    def search_one(self):
        # 查询一个文档
        user_obj = self.db.student.find_one()
        print(user_obj)

    def search_user_by_pk(self,pk):
        # 通过id查询一个文档
        obj_id = ObjectId(pk)
        user_obj = self.db.student.find_one({'_id':obj_id})
        print(user_obj)

    def search_many(self):
        # 查询多个文档
        # stu_list = self.db.student.find()
        # 查询年龄大于12岁的学生
        stu_list = self.db.student.find({"age":{"$gt":12}},{'name':1,'age':1,'_id':0})
        for item in stu_list:
            print(item)

    def paginate(self,page=1,page_size=15):
        # 分页处理
        offset = (page - 1) * page_size

        # stu_list = self.db.student.find().skip(2).limit(3)
        stu_list = self.db.student.find().skip(offset).limit(page_size)
        for item in stu_list:
            print(item)
        return stu_list


    def sort_data(self):
        # 排序
        # // 将学生的语文成绩从高到低排序
        # self.db.grades.find({"grade.course_name": "语文"}).sort({"grade.score": -1})
        # // 将学生的语文成绩按照年龄和成绩排序
        # self.db.grades.find({"grade.course_name": "语文"}).sort({"age": -1, "grade.score": -1})

        # stu_list = self.db.grades.find({"grade.course_name": "语文"}).sort({"grade.score": DESCENDING})
        # for item in stu_list:
        #     print(item)

        # 按多列排序
        stu_list = self.db.grades.find({"grade.course_name": "语文"}).sort([("age", DESCENDING),("grade.score",DESCENDING)])
        for item in stu_list:
            print(item)

    def counter_students(self):
        # 数量统计
        # result = self.db.student.count_documents({})
        result = self.db.student.count_documents({"age":{'$gt':20}})
        print(result)


    def test_aggregate(self):
        # 聚合统计：及格的学生成绩
        result = self.db.students.aggregate([
                    # //where
                    {
                        '$match':{"grades.score":{'$gte':60}}
                    },
                    # //group by
                    {
                        '$group':{
                            '_id':"$stu_no",
                            'total':{'$sum':1}
                        }
                    },
                    # //having
                    {
                        '$match':{
                            'total':{'$eq':3}
                        }
                    }
                    ])
        for item in result:
            print(item)


    # 修改一个文档
    # 替换一个文档
    # 修改多个文档
    # 一些快捷方法
    def update_one(self):
        # 修改一个文档
        result = self.db.student.update_one({}, {'$set': {'password': '123456'}})
        print(result.modified_count)

    def replace_one(self):
        # 替换一个文档
        result = self.db.student.replace_one({}, {'uname': '张三'})
        print(result.modified_count)

    def update_many(self):
        # 修改多个文档
        result = self.db.student.update_many({}, {'$set': {'password': '123456'}})
        print('修改数量',result.modified_count)
        print('满足条件的数量',result.matched_count)

    def update_shortcut(self):
        # 一些快捷方法
        # find_one_and_update
        # find_one_and_replace
        result = self.db.student.find_one_and_update({}, {'$set': {'sex': '未知'}})
        print(result)



    # 删除一个文档
    def delete_one(self):
        # 删除一个文档
        result = self.db.student.delete_one({})
        print(result.deleted_count)


    # 批量删除文档
    def delete_many(self):
        # 批量删除文档
        # result = self.db.student.delete_many({}) #这个是删除所有 危险操作
        # result = self.db.student.delete_many({"age": {'$gte':20}})
        result = self.db.student.delete_many({"name":"niha"})
        print(result.deleted_count)

    # 删除文档的快捷方法
    def delete_shortcut(self):
        # 删除文档的快捷方法
        result = self.db.student.find_one_and_delete({})
        print(result["name"])


def main():
    obj = LearnMongoDB()
    # obj.add_one()
    # obj.add_many()
    # obj.search_one()
    # obj.search_user_by_pk('686b7f9b741f0000930008f3')
    # obj.search_many()
    # obj.paginate()
    # obj.sort_data()
    # obj.counter_students()
    # obj.test_aggregate()
    # obj.update_one()
    # obj.replace_one()
    # obj.update_many()
    # obj.update_shortcut()
    # obj.delete_one()
    # obj.delete_many()
    obj.delete_shortcut()

if __name__ == '__main__':
    main()